package com.witmore.neutron.ai.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.witmore.neutron.ai.db.entity.AgentDO;
import com.witmore.neutron.ai.db.entity.AgentDeploymentDO;
import com.witmore.neutron.ai.db.mapper.AgentDeploymentMapper;
import com.witmore.neutron.ai.db.mapper.AgentMapper;
import com.witmore.neutron.ai.web.controller.vo.AgentDeploymentRequest;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.AgentDeploymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * <p>
 * 智能体部署表 服务实现类
 * </p>
 *
 * @author 豆子高
 * @since 2025-09-17
 */
@Service
public class AgentDeploymentServiceImpl implements AgentDeploymentService {

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private AgentDeploymentMapper agentDeploymentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deployAgentWithConfig(AgentDeploymentRequest request) {
        Integer userId = GlobalAccountSession.getUserInfo().getId();
        // 获取Agent信息
        AgentDO agent = agentMapper.selectById(request.getAgentId());
        if (agent == null) {
            throw new RuntimeException("智能体不存在");
        }

        if (agent.getUserId() != null && !agent.getUserId().equals(userId)) {
            throw new RuntimeException("无权限部署此智能体");
        }

        // 检查是否已经部署
        AgentDeploymentDO existingDeployment = agentDeploymentMapper.selectOne(new LambdaQueryWrapper<AgentDeploymentDO>()
                .eq(AgentDeploymentDO::getAgentId, request.getAgentId()));

        if (existingDeployment != null) {
            // 已经部署 做编辑操作
            agentDeploymentMapper.update(new LambdaUpdateWrapper<AgentDeploymentDO>()
                    .eq(AgentDeploymentDO::getAgentCode, agent.getAgentCode())
                    .eq(AgentDeploymentDO::getUserId, userId)
                    .set(StringUtils.hasText(request.getAgentIcon()), AgentDeploymentDO::getAgentIcon, request.getAgentIcon())
                    .set(StringUtils.hasText(request.getAgentName()), AgentDeploymentDO::getAgentName, request.getAgentName())
                    .set(StringUtils.hasText(request.getAgentNameAbbr()), AgentDeploymentDO::getAgentNameAbbr, request.getAgentNameAbbr())
                    .set(StringUtils.hasText(request.getAgentDesc()), AgentDeploymentDO::getAgentDesc, request.getAgentDesc())
                    .set(request.getAgentSceneTypeId() != null, AgentDeploymentDO::getAgentSceneTypeId, request.getAgentSceneTypeId())
                    .set(StringUtils.hasText(request.getConfigJson()), AgentDeploymentDO::getConfigJson, request.getConfigJson())
                    .set(AgentDeploymentDO::getUpdateTime, LocalDateTime.now()));
        } else {
            // 创建部署记录
            AgentDeploymentDO deployment = new AgentDeploymentDO();
            deployment.setAgentId(request.getAgentId());
            deployment.setAgentCode(agent.getAgentCode());
            deployment.setUserId(userId);
            deployment.setProviderId(agent.getProviderId() != null ? agent.getProviderId() : null);
            deployment.setAgentIcon(StringUtils.hasText(request.getAgentIcon()) ? request.getAgentIcon() : agent.getAgentIcon());
            deployment.setAgentName(StringUtils.hasText(request.getAgentName()) ? request.getAgentName() : agent.getAgentName());
            deployment.setAgentNameAbbr(StringUtils.hasText(request.getAgentNameAbbr()) ? request.getAgentNameAbbr() : deployment.getAgentName());
            deployment.setAgentDesc(StringUtils.hasText(request.getAgentDesc()) ? request.getAgentDesc() : agent.getAgentDesc());
            deployment.setAgentSceneTypeId(request.getAgentSceneTypeId() != null ? request.getAgentSceneTypeId() : null);
            // 默认 未发布
            deployment.setDeployStatus((byte) 2);
            deployment.setTotalChatCount(0);
            deployment.setConfigJson(request.getConfigJson());
            deployment.setCreateTime(LocalDateTime.now());
            deployment.setUpdateTime(LocalDateTime.now());

            // 保存部署记录
            agentDeploymentMapper.insert(deployment);
            // 更新Agent的部署状态
            AgentDO updateAgent = new AgentDO();
            updateAgent.setId(request.getAgentId());
            updateAgent.setDeployStatus((byte) 1);
            agentMapper.updateById(updateAgent);
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void toggleDeploymentStatus(String agentCode, Byte deployStatus) {
        // 查找部署记录
        AgentDeploymentDO deployment = agentDeploymentMapper.selectOne(new LambdaQueryWrapper<AgentDeploymentDO>()
                .eq(AgentDeploymentDO::getAgentCode, agentCode));

        if (deployment == null) {
            throw new RuntimeException("部署记录不存在");
        }
        // 状态不变无需变动
        if (deployment.getDeployStatus().equals(deployStatus)) {
            return;
        }
        // 更新部署状态
        agentDeploymentMapper.update(new LambdaUpdateWrapper<AgentDeploymentDO>()
                .eq(AgentDeploymentDO::getAgentCode, agentCode)
                .set(AgentDeploymentDO::getDeployStatus, deployStatus)
                .set(AgentDeploymentDO::getUpdateTime, LocalDateTime.now()));
        // 更新Agent的部署状态
        AgentDO updateAgent = new AgentDO();
        updateAgent.setId(deployment.getAgentId());
        updateAgent.setDeployStatus(deployStatus == 1 ? (byte) 1 : (byte) 0);
        agentMapper.updateById(updateAgent);
    }

}
